<template>
  <el-dialog 
    title="抽奖活动配置"
    :visible.sync="dialogVisible"
    width="800px"
    @close="handleClose">
    <el-form 
      :model="form"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      label-position="right">

      <!-- 基础信息 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="抽奖类型" prop="type">
            <el-radio-group v-model="form.type">
              <el-radio :label="1">普通会员</el-radio>
              <el-radio :label="2">超级会员</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="社区ID" prop="communityId">
            <el-select 
              v-model="form.communityId"
              placeholder="请选择社区"
              clearable>
              <el-option
                v-for="item in communities"
                :key="item.id"
                :label="item.communityName"
                :value="item.id"/>
            </el-select>
          </el-form-item>

          <el-form-item label="商品ID" prop="goodsId">
            <el-select
              v-model="form.goodsId"
              placeholder="请选择商品"
              clearable>
              <el-option
                v-for="item in goodsList"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="当前期数" prop="period">
            <el-input-number 
              v-model="form.period"
              :min="1"
              controls-position="right"/>
          </el-form-item>
          <el-form-item label="商品数量" prop="prizeNum">
            <el-input-number 
              v-model="form.prizeNum"
              :min="1"
              controls-position="right"/>
          </el-form-item>
          <el-form-item label="开奖时间" prop="openTime">
            <el-date-picker
              v-model="form.openTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"/>
          </el-form-item>

          <el-form-item label="截止时间" prop="endTime">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :disabledDate="disabledDate"
              placeholder="选择日期时间"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 必中名单 -->
      <el-form-item 
        label="必中用户"
        prop="raffleSpecialNameListEntities">
        <div 
          v-for="(item, index) in form.raffleSpecialNameListEntities"
          :key="index"
          class="user-item">
          <el-input
            v-model="item.userId"
            placeholder="输入用户ID"
            style="width: 200px; margin-right: 10px;"/>
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="removeUser(index)"/>
        </div>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addUser">添加用户</el-button>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    const validateUserId = (rule, value, callback) => {
      if (!/^\d+$/.test(value)) {
        callback(new Error('用户ID必须为数字'));
      } else {
        callback();
      }
    };

    return {
      dialogVisible: false,
      form: {
        id:'',
        type: 1,
        communityId: '',
        period: 1,
        goodsId: '',
        openTime: '',
        endTime: '',
        prizeNum:'',
        raffleSpecialNameListEntities: [{
          userId: ''
        }]
      },
      rules: {
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        communityId: [{ required: true, message: '请选择社区', trigger: 'change' }],
        period: [{ required: true, message: '请输入期数', trigger: 'blur' }],
        prizeNum: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        goodsId: [{ required: true, message: '请选择商品', trigger: 'change' }],
        openTime: [{ required: true, message: '请选择时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择时间', trigger: 'change' }],
        // raffleSpecialNameListEntities: [{
        //   userId: [
        //     { required: true, message: '请输入用户ID', trigger: 'blur' },
        //   ]
        // }]
      },
      communities: [], // 从接口获取
      goodsList: [] // 从接口获取
    }
  },
  methods: {
    init(id) {
      this.form.id = id;
      this.dialogVisible = true;
      this.$nextTick(() => {
        // this.$refs.ruleForm.resetFields()
        if (this.form.id) {
          this.$http({
            url: this.$http.adornUrl(
              `yshbms/raffle/info/${this.form.id}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm = data.dyb;
              console.log(this.dataForm);
            }
          });
        } else {
          this.communitiesList();
        }
      });
    },
    communitiesList() {
      this.$http({
        url: this.$http.adornUrl("yshbms/community/list"),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.communities = data.page.list;
        } else {
          this.communities = [];
        }
      });
        this.$http({
          url: this.$http.adornUrl(`yshbms/goods/list`),
          method: "post",
          data: this.$http.adornData()
        }).then(({ data }) => {
            if (data && data.code === 0) {
          this.goodsList = data.page.list;
        } else {
          this.goodsList = [];
        }
        });
    },
    openDialog() {
      this.dialogVisible = true
    },
    handleClose() {
      this.$refs.ruleForm.resetFields()
    },
    disabledDate(time) {
      return time.getTime() < Date.now()
    },
    addUser() {
      this.form.raffleSpecialNameListEntities.push({ userId: '' })
    },
    removeUser(index) {
      this.form.raffleSpecialNameListEntities.splice(index, 1)
    },
    handleSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 提交逻辑
          console.log('提交数据:', JSON.parse(JSON.stringify(this.form)))
          if (this.form.id) {
            this.$http({
              url: this.$http.adornUrl(`yshbms/raffle/update`),
              method: "post",
              data: this.$http.adornData(this.form)
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.dialogVisible = false

                    this.$emit("refreshDataList");
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          } else {
            this.$http({
              url: this.$http.adornUrl(`/yshbms/raffle/save`),
              method: "post",
              data: this.$http.adornData(this.form)
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.$emit("refreshDataList");
                    this.dialogVisible = false
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.user-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
</style>
